package com.bee.bootstrap.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.bee.bootstrap.system.entity.SmsVerify;
import com.bee.bootstrap.system.service.ISmsVerifyService;
import com.bee.common.core.enums.SmsTypeEnum;
import com.bee.common.core.enums.StatusEnum;
import com.bee.common.core.result.Result;
import com.bee.common.tools.view.RandomGeneratorUtils;
import com.bee.common.tools.view.StringTools;
import com.bee.common.tools.date.DateUtils;
import com.bee.common.tools.sms.Sms;
import com.bee.common.tools.sms.SmsAsyn;
import com.bee.bootstrap.system.mapper.SmsVerifyMapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liekkas
 * @since 2018-04-09
 */
@Service
public class SmsVerifyServiceImpl extends ServiceImpl<SmsVerifyMapper, SmsVerify> implements ISmsVerifyService {

    @Autowired
    private SmsAsyn smsAsyn;
    @Value("${sms.verify.timeout}")
    private int timeout;

    /**
     * 前后两条短信的发送时间间隔不能超过90s，防止刷短信
     * @param phone
     * @param type
     * @return
     */
    @Override
    public Result saveSendSms(String phone,String type) {
        if(!StringTools.isPhone(phone)){
            return Result.fail("手机号码错误");
        }
        if(StringUtils.isBlank(type)|| SmsTypeEnum.valueOf(type)==null){
            return Result.fail("短信类型错误");
        }
        SmsTypeEnum smsTypeEnum=SmsTypeEnum.valueOf(type);
        SmsVerify condition=new SmsVerify();
        condition.setPhone(phone);
        condition.setType(smsTypeEnum.getCode());
        condition.setStatus(StatusEnum.NORMAL.toString());
        List<SmsVerify> sms=this.selectList(new EntityWrapper<>(condition));
        if(sms!=null&&sms.size()>0){
            String authCode="";
            for(SmsVerify smsVerify:sms){
                if(smsVerify.getEndTime().after(new Date())&&DateUtils.intervalSecond(smsVerify.getCreateTime(),new Date())<=90){
                    authCode=smsVerify.getAuthCode();
                    break;
                }
            }
            if(StringUtils.isNotBlank(authCode))
                return Result.success("短信验证码发送成功",authCode);
        }
        //前面的短信失效
        sms.forEach(smsVerify -> {
            smsVerify.setStatus(StatusEnum.INVALID.toString());
        });
        if(sms!=null&&sms.size()>0)
            this.updateBatchById(sms);
        Date current=new Date();
        String authCode= RandomGeneratorUtils.generateNum(4);
        smsAsyn.addSmsAsyn(new Sms("10000",smsTypeEnum.getSmsSign(),"{\"scode\":\""+authCode+"\"}",phone,smsTypeEnum.getSmsTemplateId()));
        SmsVerify smsVerify=new SmsVerify();
        smsVerify.setAuthCode(authCode);
        smsVerify.setCreateTime(new Date());
        smsVerify.setPhone(phone);
        smsVerify.setType(smsTypeEnum.getCode());
        smsVerify.setStatus(StatusEnum.NORMAL.toString());
        smsVerify.setEndTime(DateUtils.addMinute(current,timeout));
        this.insert(smsVerify);
        return Result.success("短信验证码发送成功",authCode);
    }

    @Override
    public Result validCode(String phone, String code) {
        if(!StringTools.isPhone(phone)){
            return Result.fail("手机号码错误");
        }
        SmsVerify condition=new SmsVerify();
        condition.setPhone(phone);
        condition.setAuthCode(code);
        condition.setStatus(StatusEnum.NORMAL.toString());
        SmsVerify sms=this.selectOne(new EntityWrapper<SmsVerify>(condition));
        if(sms==null)
            return Result.fail("验证码错误");
        if(sms.getEndTime().before(new Date()))
            return Result.fail("短信验证码已过期");
        return Result.success("短信验证码通过");
    }
}
